package com.TTBook.common.config;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.TTBook.core.system.model.SysParams;
import com.TTBook.core.system.service.SysParamsService;
import com.TTBook.utils.SpringContextLoaderListener;
import com.TTBook.utils.StatusConstants;


public class ApplicationConfigUtils implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 5005293505902367703L;

	private final static Logger logger = LoggerFactory
			.getLogger(ApplicationConfigUtils.class);
	private static ApplicationConfigUtils instance = null;
	private String mallUrl;
	private String imageUrl;
	private String mallTitle;
	private Properties applicationConfig;
	private HashMap<String, Object> cacheMap;

	private static final String APPCONFIGFILE = "appConfigFile";

	private ApplicationConfigUtils() {
		try {
			String applicationFile = System.getProperty(APPCONFIGFILE);
			cacheMap = new HashMap<String, Object>();
			if (StringUtils.isEmpty(applicationFile)) {
				initPrarmData();
			} else {
				// 从虚拟机参数中指定的配置文件中读取系统配置信息
				applicationConfig = SystemConfig
						.getResourceAsPropertiesByFile(applicationFile);
			}
			mallUrl = (String) applicationConfig.get("MallUrl");
			imageUrl = (String) applicationConfig.get("ImageUrl");
			mallTitle = (String) applicationConfig.get("MallTitle");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 从数据库的系统参数配置表中读取系统配置信息
	 * 
	 * @throws Exception
	 */
	private void initPrarmData() throws Exception {
		SysParamsService sysParamsService = (SysParamsService) SpringContextLoaderListener
				.getSpringWebApplicationContext().getBean("sysParamsService");
		List<SysParams> dataList = sysParamsService.getSysParamsPage(null, 0,
				Integer.MAX_VALUE);
		Iterator<SysParams> iterator = dataList.iterator();
		applicationConfig = new Properties();
		while (iterator.hasNext()) {
			SysParams sysParams = (SysParams) iterator.next();
			cacheMap.put(sysParams.getInnerName(), sysParams);
			// 值为空或是动态参数不加载到内存中。
			if (StringUtils.isEmpty(sysParams.getInnerName())
					|| StringUtils.isEmpty(sysParams.getValue())
					|| StatusConstants.SYS_PARAM_D_VALUE.equals(sysParams.getType())) {
				continue;
			}
			applicationConfig.put(sysParams.getInnerName(),
					sysParams.getValue());
		}
	}

	/**
	 * 根据key取缓存数据，如果非静态则动态读库数据
	 * 
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public String getPropertiesValue(String key) {
		try {
			SysParamsService sysParamsService = (SysParamsService) SpringContextLoaderListener
					.getSpringWebApplicationContext().getBean(
							"sysParamsService");
			if (cacheMap.containsKey(key)) {
				SysParams obj = (SysParams) cacheMap.get(key);
				if (obj.getType().equals(StatusConstants.SYS_PARAM_D_VALUE)) {
					obj = sysParamsService.getSysParams(key);
					return obj.getValue();
				} else {
					return (String) applicationConfig.getProperty(key);
				}
			} else {
				SysParams obj = sysParamsService.getSysParams(key);
				if (obj != null) {
					cacheMap.put(obj.getInnerName(), obj);
					if (obj.getType().equals(StatusConstants.SYS_PARAM_S_VALUE)) {
						applicationConfig.put(obj.getInnerName(),
								obj.getValue());
					}
					return obj.getValue();
				} else {
					return null;
				}
			}
		} catch (Exception e) {
			return null;
		}
	}

	public static void reload() throws Exception {
		instance = null;
	}

	public static ApplicationConfigUtils getInstance() {
		if (instance == null) {
			instance = new ApplicationConfigUtils();
		}
		return instance;
	}

	public String getMallUrl() {
		return mallUrl;
	}

	public String getImageUrl() {
		return imageUrl;
	}

	public String getMallTitle() {
		return mallTitle;
	}
	public ApplicationConfigUtils removeCacheKey(String key) {
		cacheMap.remove(key);
		return this;
	}

}
